<template>
  <div class="pf-flow-design-list pf-bgwhite">
    <div class="pf-p-10">
      <el-button type="primary" @click="handleAdd">新增</el-button>
    </div>
    <pf-table
      :data="datas"
      :config="tableConfig"
      :page-param="pageParam"
      @page-size-change="pageSizeChange"
      @page-change="pageChange"
      @current-page-change="pageChange"
    >
      <el-table-column label="流程ID" prop="id" min-width="100px" show-overflow-tooltip />
      <el-table-column label="流程Key" prop="key" min-width="100px" show-overflow-tooltip />
      <el-table-column label="流程名称" prop="name" min-width="100px" show-overflow-tooltip />
      <!--      <el-table-column label="租户ID" prop="tenantId" min-width="100px" show-overflow-tooltip />-->
      <!--      <el-table-column label="发布ID" prop="deploymentId" min-width="100px" show-overflow-tooltip />-->
      <el-table-column label="发布版本" prop="version" min-width="100px" show-overflow-tooltip />
      <!--      <el-table-column label="发布版本Tag" prop="versionTag" min-width="100px" show-overflow-tooltip />-->
      <el-table-column
        label="diagram名称"
        prop="diagramResourceName"
        min-width="100px"
        show-overflow-tooltip
      />
      <el-table-column
        label="文件名称"
        prop="resourceName"
        min-width="100px"
        show-overflow-tooltip
      />
      <el-table-column label="描述" prop="description" min-width="100px" show-overflow-tooltip />
      <el-table-column
        label="StartForm"
        prop="startFormKey"
        min-width="100px"
        show-overflow-tooltip
      />
      <el-table-column label="操作" width="100px">
        <template v-slot="{ row }">
          <el-button size="mini" link type="primary" @click="handleClick('del', row)"
            >删除</el-button
          >
          <el-button size="mini" link type="primary" @click="handleClick('edit', row)"
            >修改</el-button
          >
          <el-button size="mini" link type="primary" @click="handleClick('start', row)"
            >发起</el-button
          >
        </template>
      </el-table-column>
    </pf-table>
    <el-dialog title="创建流程" width="90%" :fullscreen="true" :top="'10vh'" v-model="dialogVis">
      <FlowDesign :is-custom-panel="true" :xml="currentFlowXml"></FlowDesign>
      <template v-slot:footer>
        <el-button type="primary" @click="handleDoAdd">保存</el-button>
        <el-button @click="handleCancelAdd">取消</el-button>
      </template>
    </el-dialog>
    <el-dialog title="发单信息" width="70%" v-model="startFormDialogVis">
      <pf-form ref="startFormDom" :config="startFormConfig" :model="startFormData"></pf-form>
      <template v-slot:footer>
        <el-button type="primary" @click="doFlowStart">提交</el-button>
        <el-button type="primary">暂存</el-button>
        <el-button @click="cancelFlowStart">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, Ref } from 'vue';
import FlowDesign from '@/views/page-config/flow/FlowDesign.vue';
import { camundaApi } from '@/constants/api/camunda-api';
import {
  emptyForm,
  emptyTable,
  FormModel,
  ResponseCodeEnum,
  TableModel,
  useData,
  useHttpClient
} from 'pf-component';
import { useNotice } from '@/components/element-plus/notice';
import { initTemplate } from '@/views/page-config/flow/default-flow';
import { modeler } from '@/views/page-config/flow/flow-modeler';

export default defineComponent({
  name: 'FlowDesignList',
  components: { FlowDesign },
  setup() {
    const tableConfig: Ref<TableModel> = ref(emptyTable);
    tableConfig.value.showPage = true;
    const datas: Ref = ref([]);
    const pageParam: any = reactive({ total: 0, pageSize: 10, pageNum: 1 });
    const currentFlowXml: Ref<string> = ref(initTemplate());
    const dialogVis: Ref<boolean> = ref(false);
    const handleAdd = () => {
      currentFlowXml.value = initTemplate();
      dialogVis.value = true;
    };

    const startFormDom: Ref = ref(null);
    const startFormData: Ref = ref({});
    const startFormConfig: Ref<FormModel> = ref(emptyForm);

    const startFlowId = ref('');
    const startFlowBizKey = ref('');
    const startFormDialogVis: Ref<boolean> = ref(false);
    const handleFlowStart = (formKey: string) => {
      startFormDialogVis.value = true;
      const forms = [];
      formKey && forms.push({ name: formKey, config: startFormConfig, info: startFormData });
      forms.length &&
        useData()
          .loadForm(forms)
          .then(res => {});
    };
    const cancelFlowStart = () => {
      startFormDialogVis.value = false;
    };
    const doFlowStart = () => {
      if (startFlowId.value && startFlowBizKey.value) {
        useHttpClient()
          .general(
            camundaApi.processApi.startById,
            { keyOrId: startFlowId.value, bizKey: startFlowBizKey.value },
            { ...startFormData.value }
          )
          .then(res => {
            if (ResponseCodeEnum.SUCCESS === res.code) {
              useNotice().message.success('success:' + res.message);
            } else {
              useNotice().message.error(res.message);
            }
          });
      }
    };

    const initDatas = () => {
      const loading = useNotice().loading;
      loading.open();
      useHttpClient()
        .general(camundaApi.processApi.deployList, undefined, pageParam)
        .then(res => {
          if (res.code === ResponseCodeEnum.SUCCESS) {
            const { records, total } = res.data as any;
            datas.value = records;
            pageParam.total = total;
          } else {
            datas.value = [];
            pageParam.total = 0;
          }
        })
        .finally(() => {
          loading.close();
        });
    };
    initDatas();
    const pageChange = (val: number) => {
      pageParam.pageNum = val;
      initDatas();
    };
    const pageSizeChange = (val: number) => {
      pageParam.pageSize = val;
      initDatas();
    };
    const handleClick = (cmd: string, data: any) => {
      if (cmd === 'edit') {
        useHttpClient()
          .general<any>(camundaApi.processApi.getResource, {
            deploymentId: data.deploymentId,
            resourceName: data.resourceName
          })
          .then(res => {
            currentFlowXml.value = res.data;
            dialogVis.value = true;
          });
      } else if (cmd === 'start') {
        startFlowId.value = data.id;
        startFlowBizKey.value = 'wj-test-biz-key';
        if (data.startFormKey) {
          handleFlowStart(data.startFormKey);
        } else {
          doFlowStart();
        }
      } else if (cmd === 'del') {
        useHttpClient()
          .general(camundaApi.processApi.del, { id: data.deploymentId })
          .then(res => {
            if (ResponseCodeEnum.SUCCESS === res.code) {
              useNotice().message.success('success:' + res.message);
              initDatas();
            } else {
              useNotice().message.error(res.message);
            }
          });
      }
    };
    const handleDoAdd = () => {
      modeler
        .getModeler()
        .saveXML({ format: true })
        .then((data: any) => {
          const { err, xml } = data;
          if (err || !xml) {
            useNotice().message.error(`[Process Designer Warn ]: ${err?.message || err}`);
          } else {
            const name = '测试';
            const resource = xml;
            const resourceName = 'testSource';
            useHttpClient()
              .general<any>(camundaApi.processApi.deploy, { name }, { resource, resourceName })
              .then(res => {
                if (res.code === ResponseCodeEnum.SUCCESS) {
                  useNotice().message.success('success');
                  dialogVis.value = false;
                  initDatas();
                } else {
                  useNotice().message.error(res.message);
                }
              });
          }
        });
    };
    const handleCancelAdd = () => {
      useNotice().message.warning('cancel');
      dialogVis.value = false;
    };
    return {
      datas,
      pageParam,
      pageChange,
      pageSizeChange,
      tableConfig,
      dialogVis,
      handleClick,
      handleAdd,
      handleDoAdd,
      handleCancelAdd,
      currentFlowXml,
      startFormDialogVis,
      doFlowStart,
      cancelFlowStart,
      startFormConfig,
      startFormData,
      startFormDom
    };
  }
});
</script>
<style scoped lang="scss">
.#{$prefix} {
  &-flow-design-list {
    //margin: 10px;
    //padding: 0;
    //overflow-y: auto;
    height: 100%;
  }
}
</style>
